// 交易面板窗口管理组合式函数

import { ref } from 'vue'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { LogicalPosition, PhysicalPosition } from '@tauri-apps/api/window'
import { useMonitorManager } from '../useMonitorManager'
import { SyncConfigManager, type SyncConfig } from '@/config/syncConfig'

// 简单的通知函数
const showNotification = (message: string) => {
  console.log(`📢 ${message}`)
  // 可以在这里添加其他通知方式，比如显示一个临时的提示框
}

export function useTradingPanels() {
  // 交易面板窗口管理
  const tradingPanels = ref<Map<string, WebviewWindow>>(new Map())

  // 合约代码映射，用于跟踪每个面板的合约代码
  const panelContractMap = ref<Map<string, string>>(new Map())

  // 显示器管理
  const { matchMonitor, calculateWindowPosition, getPrimaryMonitor } = useMonitorManager()

  // 同步模式状态 - 默认开启
  const isSyncMode = ref(true)
  const syncListeners = new Map<string, () => void>()

  // 节流定时器映射，用于控制同步频率
  const throttleTimers = new Map<string, NodeJS.Timeout>()

  // 防抖定时器映射，用于减少拖动抖动
  const debounceTimers = new Map<string, NodeJS.Timeout>()

  // 同步操作标志，防止同步操作触发的resize事件再次触发同步
  const syncInProgress = ref(new Set<string>())

  // 上次同步时间映射，用于节流控制
  const lastSyncTime = new Map<string, number>()

  // 同步状态持久化
  const SYNC_MODE_KEY = 'trading_panels_sync_mode'

  // 初始化同步模式状态（从localStorage恢复）
  const initializeSyncMode = () => {
    try {
      const saved = localStorage.getItem(SYNC_MODE_KEY)
      if (saved !== null) {
        isSyncMode.value = JSON.parse(saved)
      }
    } catch (error) {
      console.error('恢复同步模式状态失败:', error)
      isSyncMode.value = true // 默认开启
    }
  }

  // 保存同步模式状态
  const saveSyncMode = () => {
    try {
      localStorage.setItem(SYNC_MODE_KEY, JSON.stringify(isSyncMode.value))
    } catch (error) {
      console.error('保存同步模式状态失败:', error)
    }
  }

  // 获取当前同步配置
  const getSyncConfig = (): SyncConfig => SyncConfigManager.getCurrentConfig()

  // 检查指定集合是否有活跃的窗口
  const hasActivePanels = (setNumber: number): boolean => {
    return Array.from(tradingPanels.value.keys())
      .some(id => id.startsWith(`trading-panel-${setNumber}-`))
  }

  // 获取指定集合的所有窗口
  const getSetPanels = (setNumber: number): [string, WebviewWindow][] => {
    return Array.from(tradingPanels.value.entries())
      .filter(([id]) => id.startsWith(`trading-panel-${setNumber}-`))
  }

  // 打开交易面板
  const openTradingPanel = async (options: { setNumber: number, tradeName?: string, contractCode?: string, windowConfig?: any, priceTick?: number }) => {
    const { setNumber, tradeName, contractCode, windowConfig, priceTick } = options
    try {
      // 如果有合约代码，检查是否已存在相同合约的窗口
      if (contractCode) {
        // 检查合约代码映射中是否已存在此合约
        const contractEntries = Array.from(panelContractMap.value.entries())
        for (const [panelId, existingContractCode] of contractEntries) {
          if (existingContractCode === contractCode && tradingPanels.value.has(panelId)) {
            showNotification(`该合约已经打开: ${contractCode}`)
            return
          }
        }
      }

      // 创建新窗口
      const timestamp = Date.now()
      // 如果有指定的panelId则使用，否则生成新的
      const panelId = windowConfig?.panelId || `trading-panel-${setNumber}-${timestamp}`

      // 立即添加到管理列表，防止重复创建
      tradingPanels.value.set(panelId, null as any) // 临时占位

      // 如果有合约代码，记录到映射中
      if (contractCode) {
        panelContractMap.value.set(panelId, contractCode)
      }

      // 计算窗口位置
      let windowX: number, windowY: number, windowWidth: number, windowHeight: number

      if (windowConfig) {
        // 使用配置中的位置和大小
        windowX = windowConfig.x || 200
        windowY = windowConfig.y || 150
        windowWidth = windowConfig.width || 200
        windowHeight = windowConfig.height || 800

        // 根据显示器标识和编号调整窗口位置
        if (windowConfig.screenNumber || windowConfig.monitorId || windowConfig.monitorName) {
          try {
            const { monitor, method } = await matchMonitor({
              monitorName: windowConfig.monitorName,
              monitorId: windowConfig.monitorId,
              screenNumber: windowConfig.screenNumber,
              x: windowConfig.x,
              y: windowConfig.y
            })

            if (monitor) {
              // 配置加载时，windowConfig中的x,y已经是绝对坐标，直接使用
              windowX = windowConfig.x
              windowY = windowConfig.y

            } else {
              // 确保窗口坐标在主显示器范围内
              const primaryMonitor = await getPrimaryMonitor()
              if (primaryMonitor) {
                windowX = Math.max(primaryMonitor.position.x, Math.min(windowConfig.x, primaryMonitor.position.x + primaryMonitor.size.width - windowWidth))
                windowY = Math.max(primaryMonitor.position.y, Math.min(windowConfig.y, primaryMonitor.position.y + primaryMonitor.size.height - windowHeight))
              }
            }
          } catch (error) {
          }
        } else {
        }
      } else {
        // 默认位置计算
        const offsetX = (setNumber - 1) * 50 // 根据集合编号偏移
        const offsetY = (setNumber - 1) * 50
        windowX = 200 + offsetX
        windowY = 150 + offsetY
        windowWidth = 200
        windowHeight = 800
      }

      // 构建URL，如果有合约代码则通过查询参数传递
      let url = '#/trading-panel'
      if (contractCode) {
        url += `?contract=${encodeURIComponent(contractCode)}`
        if (priceTick) {
          url += `&priceTick=${priceTick}`
        }
      }

      const panel = new WebviewWindow(panelId, {
        url,
        title: tradeName,
        width: windowWidth,
        height: windowHeight,
        minWidth: 200,
        minHeight: 400,
        resizable: true,
        decorations: false,
        alwaysOnTop: false,
        center: false,
        skipTaskbar: false,
        visible: false  // 先不显示，等设置位置后再显示
      })

      // 监听窗口创建成功
      panel.once('tauri://created', async () => {
        tradingPanels.value.set(panelId, panel) // 替换临时占位
        try {
          // 等待一小段时间确保窗口完全初始化
          await new Promise(resolve => setTimeout(resolve, 200))

          // 显式设置窗口位置
          await panel.setPosition(new PhysicalPosition(windowX, windowY))
          // 确保窗口可见并获得焦点
          await panel.show()

          // 如果有指定的窗口配置，进行额外的位置验证和调整
          if (windowConfig) {
            // 对于其他显示器的窗口，增加额外的验证和调整
            const isSecondaryMonitor = windowConfig.screenNumber > 1 ||
              (windowConfig.monitorId && windowConfig.monitorId !== '0_0_1920_1080')

            if (isSecondaryMonitor) {
              // 再次等待确保窗口完全显示
              await new Promise(resolve => setTimeout(resolve, 500))

              // 验证窗口实际位置
              try {
                const actualPosition = await panel.outerPosition()

                // 如果位置不正确，再次设置
                const tolerance = 10 // 允许10像素的误差
                if (Math.abs(actualPosition.x - windowX) > tolerance || Math.abs(actualPosition.y - windowY) > tolerance) {
                  await panel.setPosition(new LogicalPosition(windowX, windowY))
                  await new Promise(resolve => setTimeout(resolve, 200))
                }
              } catch (posError) {
              }
            }
          }

          await panel.setFocus()

          // 如果同步模式已开启，为新创建的面板设置同步监听器
          if (isSyncMode.value) {
            await setupSyncListenerForPanel(panelId, panel, setNumber)
          }
        } catch (error) {
          // 即使位置设置失败，也要确保窗口可见
          try {
            await panel.show()
            
            // 即使出现错误，也尝试设置同步监听器
            if (isSyncMode.value) {
              await setupSyncListenerForPanel(panelId, panel, setNumber)
            }
          } catch (showError) {
          }
        }
      })

      // 监听窗口创建错误
      panel.once('tauri://error', (error) => {
        tradingPanels.value.delete(panelId) // 清理失败的窗口
      })

      // 监听窗口关闭
      panel.once('tauri://close-requested', () => {
        tradingPanels.value.delete(panelId)
        // 清理合约代码映射
        panelContractMap.value.delete(panelId)
        // 清理同步监听器
        if (syncListeners.has(panelId)) {
          const unlisten = syncListeners.get(panelId)
          if (unlisten) {
            unlisten()
          }
          syncListeners.delete(panelId)
        }
      })

      // 监听窗口销毁（确保清理）
      panel.once('tauri://destroyed', () => {
        if (tradingPanels.value.has(panelId)) {
          tradingPanels.value.delete(panelId)
          panelContractMap.value.delete(panelId)
        }
      })

      // 监听窗口创建失败
      panel.once('tauri://error', (error) => {
        // 清理临时占位
        tradingPanels.value.delete(panelId)
        panelContractMap.value.delete(panelId)
      })

    } catch (error) {
    }
  }

  // 隐藏所有交易面板
  const hideAllTradingPanels = async () => {
    try {
      const panelEntries = Array.from(tradingPanels.value.entries())

      if (panelEntries.length === 0) {
        return
      }

      for (const [panelId, panel] of panelEntries) {
        try {
          // 检查面板是否有效（不是临时占位符）
          if (panel && typeof panel.hide === 'function') {
            await panel.hide()
          } else {
          }
        } catch (error) {
          // 继续隐藏其他面板，不因单个面板失败而中断
        }
      }

    } catch (error) {
    }
  }

  // 隐藏指定交易集的面板
  const hideSetPanels = async (setNumber: number) => {
    try {
      const panelsToHide = getSetPanels(setNumber)

      if (panelsToHide.length === 0) {
        return
      }

      for (const [id, panel] of panelsToHide) {
        try {
          if (panel && typeof panel.hide === 'function') {
            await panel.hide()
          }
        } catch (error) {
        }
      }

    } catch (error) {
    }
  }

  // 显示所有交易面板
  const showAllTradingPanels = async () => {
    try {
      const panelEntries = Array.from(tradingPanels.value.entries())

      if (panelEntries.length === 0) {
        return
      }


      for (const [panelId, panel] of panelEntries) {
        try {
          // 检查面板是否有效（不是临时占位符）
          if (panel && typeof panel.show === 'function') {
            await panel.show()
          } else {
          }
        } catch (error) {
          // 继续显示其他面板，不因单个面板失败而中断
        }
      }

    } catch (error) {
    }
  }

  // 显示指定交易集的面板
  const showSetPanels = async (setNumber: number) => {
    try {
      const panelsToShow = getSetPanels(setNumber)
      if (panelsToShow.length === 0) {
        return
      }
      for (const [id, panel] of panelsToShow) {
        try {
          if (panel && typeof panel.show === 'function') {
            // 显示窗口
            await panel.show()
            // 取消最小化状态（如果窗口被最小化）
            if (typeof panel.unminimize === 'function') {
              await panel.unminimize()
            }

            // 激活窗口并置顶
            if (typeof panel.setFocus === 'function') {
              await panel.setFocus()
            }
          }
        } catch (error) { }
      }
    } catch (error) { }
  }

  // 关闭指定交易集的面板
  const closeAllPanels = async (setNumber: number) => {
    try {
      const panelsToClose = getSetPanels(setNumber)

      if (panelsToClose.length === 0) {
        return
      }

      const [id, panel] = panelsToClose[0] // 现在每个集合只有一个面板
      await panel.close()
      tradingPanels.value.delete(id)

    } catch (error) { }
  }

  // 切换同步模式
  const toggleSyncMode = async (setNumber: number) => {
    isSyncMode.value = !isSyncMode.value
    
    // 保存同步模式状态
    saveSyncMode()

    if (isSyncMode.value) {
      // 启用同步模式
      await enableSyncMode(setNumber)
    } else {
      // 关闭同步模式
      disableSyncMode()
    }
  }

  // 为单个面板设置同步监听器
  const setupSyncListenerForPanel = async (panelId: string, panel: WebviewWindow, setNumber: number) => {
    try {
      if (panel && typeof panel.onResized === 'function') {
        const unlisten = await panel.onResized(async () => {
          if (isSyncMode.value && !syncInProgress.value.has(panelId)) {
            await throttledSyncAllPanelsToReference(setNumber, panelId)
          }
        })
        syncListeners.set(panelId, unlisten)
        console.log(`🔄 已为面板 ${panelId} 设置同步监听器`)
      }
    } catch (error) {
      console.error(`为面板 ${panelId} 设置同步监听器失败:`, error)
    }
  }

  // 启用同步模式
  const enableSyncMode = async (setNumber: number) => {
    try {
      const panelsToSync = getSetPanels(setNumber)

      if (panelsToSync.length === 0) {
        isSyncMode.value = false
        return
      }

      if (panelsToSync.length === 1) {
        return
      }

      // 为每个面板添加大小变化监听器
      for (const [panelId, panel] of panelsToSync) {
        await setupSyncListenerForPanel(panelId, panel, setNumber)
      }
      console.log(`🔄 已为交易集 ${setNumber} 的 ${panelsToSync.length} 个面板启用同步模式`)
    } catch (error) {
      console.error('启用同步模式失败:', error)
      isSyncMode.value = false
    }
  }

  // 关闭同步模式
  const disableSyncMode = () => {
    // 移除所有监听器
    syncListeners.forEach((unlisten, panelId) => {
      try {
        unlisten()
      } catch (error) {
        console.error(`移除面板${panelId}监听器失败:`, error)
      }
    })
    syncListeners.clear()

    // 清理所有节流定时器
    throttleTimers.forEach((timer, panelId) => {
      clearTimeout(timer)
    })
    throttleTimers.clear()

    // 清理所有防抖定时器
    debounceTimers.forEach((timer, panelId) => {
      clearTimeout(timer)
    })
    debounceTimers.clear()

    // 清理同步状态和时间记录
    syncInProgress.value.clear()
    lastSyncTime.clear()
  }

  // 带防抖和节流的实时同步函数
  const throttledSyncAllPanelsToReference = async (setNumber: number, referencePanelId: string) => {
    const config = getSyncConfig()
    // 清除之前的防抖定时器
    const existingDebounceTimer = debounceTimers.get(referencePanelId)
    if (existingDebounceTimer) {
      clearTimeout(existingDebounceTimer)
    }

    // 设置防抖定时器，减少拖动抖动
    const debounceTimer = setTimeout(async () => {
      await throttledExecuteSync(setNumber, referencePanelId)
      debounceTimers.delete(referencePanelId)
    }, config.debounceDelay)

    debounceTimers.set(referencePanelId, debounceTimer)
  }

  // 节流执行同步
  const throttledExecuteSync = async (setNumber: number, referencePanelId: string) => {
    const config = getSyncConfig()
    const now = Date.now()
    const lastSync = lastSyncTime.get(referencePanelId) || 0
    const timeSinceLastSync = now - lastSync

    // 如果距离上次同步时间不足节流间隔，则设置定时器延后执行
    if (timeSinceLastSync < config.throttleDelay) {
      const delay = config.throttleDelay - timeSinceLastSync

      // 清除之前的节流定时器
      const existingTimer = throttleTimers.get(referencePanelId)
      if (existingTimer) {
        clearTimeout(existingTimer)
      }

      // 设置新的节流定时器
      const timer = setTimeout(async () => {
        await executeSyncAllPanelsToReference(setNumber, referencePanelId)
        await executeSyncAllPanelsToReference(setNumber, referencePanelId)
        throttleTimers.delete(referencePanelId)
      }, delay)

      throttleTimers.set(referencePanelId, timer)
      return
    }
    // 立即执行同步
    await executeSyncAllPanelsToReference(setNumber, referencePanelId)
  }

  // 执行同步操作的核心函数
  const executeSyncAllPanelsToReference = async (setNumber: number, referencePanelId: string) => {
    try {
      const panelsToSync = getSetPanels(setNumber)
      const referencePanel = tradingPanels.value.get(referencePanelId)

      if (!referencePanel || typeof referencePanel.outerSize !== 'function') {
        console.log(`🔄 同步失败: 参考面板无效 ${referencePanelId}`)
        return
      }

      // 检查是否有足够的面板进行同步
      if (panelsToSync.length < 2) {
        console.log(`🔄 同步跳过: 面板数量不足 (${panelsToSync.length})`)
        return
      }

      // 更新最后同步时间
      lastSyncTime.set(referencePanelId, Date.now())

      // 获取参考面板的大小和位置
      const referenceSize = await referencePanel.outerSize()
      const referencePosition = await referencePanel.outerPosition()
      console.log(`🔄 开始同步: 参考面板 ${referencePanelId}, 目标尺寸: ${referenceSize.width}x${referenceSize.height}, 位置: ${referencePosition.x},${referencePosition.y}`)

      // 标记所有面板为同步中状态，防止循环触发
      const allPanelIds = panelsToSync.map(([id]) => id)
      allPanelIds.forEach(id => syncInProgress.value.add(id))

      try {
        // 同步其他面板 - 使用串行执行避免并发问题
        let syncCount = 0
        
        for (const [panelId, panel] of panelsToSync) {
          if (panelId !== referencePanelId && panel && typeof panel.setSize === 'function' && typeof panel.setPosition === 'function') {
            try {
              // 同步大小
              await panel.setSize(referenceSize)
              
              // 获取当前面板的位置，保持其原始的X坐标
              const currentPosition = await panel.outerPosition()
              const newPosition = new LogicalPosition(
                currentPosition.x, // 保持原始的X坐标（距离左侧的距离）
                referencePosition.y // 使用参考面板的Y坐标，实现水平对齐
              )
              
              // 同步位置（只改变Y坐标）
              await panel.setPosition(newPosition)
              
              syncCount++
              console.log(`🔄 同步成功: 面板 ${panelId}, 保持X坐标: ${currentPosition.x}, 同步Y坐标: ${referencePosition.y}`)
              
              // 添加小延迟，确保窗口系统有时间处理
              await new Promise(resolve => setTimeout(resolve, 30))
            } catch (error) {
              console.error(`🔄 同步失败: 面板 ${panelId}`, error)
            }
          }
        }

        console.log(`🔄 同步完成: 成功同步 ${syncCount} 个面板到水平线上`)

      } finally {
        // 短暂延迟后清除同步状态，确保resize事件处理完毕
        const config = getSyncConfig()
        setTimeout(() => {
          allPanelIds.forEach(id => syncInProgress.value.delete(id))
          console.log(`🔄 清除同步状态: ${allPanelIds.length} 个面板`)
        }, config.syncStateDelay) // 使用配置的延迟时间
      }

    } catch (error) {
      console.error('🔄 同步执行失败:', error)
    }
  }

  // 手动同步指定交易集的所有面板大小和位置（一次性操作）
  const syncSetPanels = async (setNumber: number) => {
    try {
      const panelsToSync = getSetPanels(setNumber)
      if (panelsToSync.length === 0) {
        return
      }

      if (panelsToSync.length === 1) {
        return
      }

      // 获取第一个面板作为参考面板
      const [referenceId, referencePanel] = panelsToSync[0]

      if (!referencePanel || typeof referencePanel.outerSize !== 'function') {
        return
      }

      // 获取参考面板的大小和位置
      const referenceSize = await referencePanel.outerSize()
      const referencePosition = await referencePanel.outerPosition()

      // 同步其他面板
      let syncCount = 0
      
      for (let i = 1; i < panelsToSync.length; i++) {
        const [panelId, panel] = panelsToSync[i]

        try {
          if (panel && typeof panel.setSize === 'function' && typeof panel.setPosition === 'function') {
            // 设置相同的大小
            await panel.setSize(referenceSize)

            // 获取当前面板的位置，保持其原始的X坐标
            const currentPosition = await panel.outerPosition()
            const newPosition = new LogicalPosition(
              currentPosition.x, // 保持原始的X坐标（距离左侧的距离）
              referencePosition.y // 使用参考面板的Y坐标，实现水平对齐
            )
            await panel.setPosition(newPosition)

            syncCount++
            console.log(`🔄 手动同步: 面板 ${panelId}, 保持X坐标: ${currentPosition.x}, 同步Y坐标: ${referencePosition.y}`)
          }
        } catch (error) {
          console.error(`手动同步失败: 面板 ${panelId}`, error)
        }
      }
      
      console.log(`🔄 手动同步完成: 成功同步 ${syncCount} 个面板到水平线上`)
    } catch (error) {
      console.error('手动同步失败:', error)
    }
  }

  // 关闭所有面板
  const closeAllTradingPanels = async () => {
    try {
      const panelEntries = Array.from(tradingPanels.value.entries())
      for (const [panelId, panel] of panelEntries) {
        try {
          // 检查面板是否有效（不是临时占位符）
          if (panel && typeof panel.close === 'function') {
            await panel.close()
          }
        } catch (error) {
          console.error(`关闭面板 ${panelId} 失败:`, error)
        }
      }

      // 清空面板映射和合约映射
      tradingPanels.value.clear()
      panelContractMap.value.clear()
    } catch (error) {
      console.error('关闭所有面板失败:', error)
    }
  }

  // 初始化同步功能
  const initializeSync = async () => {
    try {
      console.log(`🔄 初始化同步功能，当前同步模式: ${isSyncMode.value}`)
      
      if (isSyncMode.value) {
        // 为所有现有面板设置同步监听器
        const allPanels = Array.from(tradingPanels.value.entries())
        for (const [panelId, panel] of allPanels) {
          if (panel && typeof panel.onResized === 'function') {
            // 从panelId中提取setNumber
            const match = panelId.match(/trading-panel-(\d+)-/)
            if (match) {
              const setNumber = parseInt(match[1])
              await setupSyncListenerForPanel(panelId, panel, setNumber)
            }
          }
        }
        console.log(`🔄 同步功能初始化完成，已为 ${allPanels.length} 个面板设置监听器`)
      }
    } catch (error) {
      console.error('初始化同步功能失败:', error)
    }
  }

  // 初始化同步模式状态
  initializeSyncMode()

  return {
    tradingPanels,
    isSyncMode,
    hasActivePanels,
    getSetPanels,
    openTradingPanel,
    hideAllTradingPanels,
    showAllTradingPanels,
    hideSetPanels,
    showSetPanels,
    closeAllPanels,
    closeAllTradingPanels,
    syncSetPanels,
    toggleSyncMode,
    initializeSyncMode,
    initializeSync
  }
}
